﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SqlSugar.Extensions;

namespace DT.Application.Api
{
    /// <summary>
    /// 登录服务
    /// </summary>
    [AppAuthorize, ApiDescriptionSettings("登录管理")]
    public class LoginApiService : IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// LoginApiService
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public LoginApiService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// [AllowAnonymous] 匿名访问
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public string UserLogin()
        {
            // 生成 token
            //var jwtSettings = App.GetOptions<JWTSettingsOptions>();

            var jwtSettings = App.Configuration.GetSection("JWTSettings").Get<JWTSettingsOptions>();

            var datetimeOffset = DateTimeOffset.UtcNow;

            // 生成 token
            string _token = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary<string, object>()
            {
                { "UserId", "1" },  // 存储Id
                { "LoginCode","xush" }, // 存储用户名
                { "RoleId", "admin"}, // 存储角色ID
                { "UserIP", ""}, // IP地址
                { "AppType", ""}, // 客户端类型

                // 登录时间 2005-11-5 5:21:25
                //{ "LoginTime", DateTime.Now.ToUniversalTime().ToString()},

                //iss: jwt签发者
                //sub: jwt所面向的用户
                //aud: 接收jwt的一方
                //exp: jwt的过期时间，这个过期时间必须要大于签发时间
                //nbf: 定义在什么时间之前，该jwt都是不可用的.
                //iat: jwt的签发时间
                //jti: jwt的唯一身份标识，主要用来作为一次性token,从而回避重放攻击

                { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() },
                { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() },
                { JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddSeconds(jwtSettings.ExpiredTime.Value * 60).ToUnixTimeSeconds() },
                { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer},
                { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience }
        });

            // 设置 Swagger 刷新自动授权
            _httpContextAccessor.SigninToSwagger(_token);

            // 获取刷新 token
            var refreshToken = JWTEncryption.GenerateRefreshToken(_token, 30); // 第二个参数是刷新 token 的有效期，默认三十天

        // 设置请求报文头
        _httpContextAccessor.HttpContext.Response.Headers["access-token"] = _token;
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;

            return "登录成功！！！token：" + _token;
        }
}
}
